﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Windows.Forms;
using System.Diagnostics;

namespace Homebrew_SD_Manager
{
    class Update
    {
        string version;

        #region Version.txt
        public void init_reseau(string ver)
        {
            version = ver;
            try
            {
                HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("http://homebrewsdmanager.googlecode.com/svn/trunk/update/version.txt");
                HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
                WebClient clientWeb = new WebClient();
                Uri url = new Uri("http://homebrewsdmanager.googlecode.com/svn/trunk/update/version.txt");
                clientWeb.DownloadFileAsync(url, "version.txt");
                clientWeb.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(clientWeb_DownloadFileCompleted);
            }
            catch
            { }
        }

        void clientWeb_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            update();
        }
        #endregion

        #region Update
        public void update()
        {
            string ver = File.ReadAllText("version.txt");
            if (ver != version)
            {
                DialogResult di = MessageBox.Show("La version " + ver + " est disponible, voulez-vous mettre Homebrew SD Manager à jour ?", "Mise à jour", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (di == DialogResult.Yes)
                {
                    WebClient clientWeb1 = new WebClient();
                    Uri url = new Uri("http://homebrewsdmanager.googlecode.com/svn/trunk/update/updater.exe");
                    clientWeb1.DownloadFileAsync(url, "updater.exe");
                    clientWeb1.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(clientWeb1_DownloadFileCompleted);
                }
            }
            else
            {
                File.Delete("updater.exe");
            }
            File.Delete("version.txt");
        }

        void clientWeb1_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            MessageBox.Show("La mise à jour va commencer", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
            Process.Start("Updater.exe");
            Application.Exit();
        }
        #endregion
    }
}
